// 存储所有 API 类型数据
let apiTypesData = null;

// 加载 API 类型数据
async function loadAPITypes() {
    try {
        const response = await fetch('/api/types');
        const data = await response.json();
        console.log('Loaded API types data:', data);
        apiTypesData = data.APITypes;
        initializeAPITypeSelectors();
    } catch (error) {
        console.error('Error loading API types:', error);
        showError('Error loading API types. Please try again later.');
    }
}

// 初始化 API Type 选择器
function initializeAPITypeSelectors() {
    const selectors = document.querySelectorAll('.api-type-select');
    selectors.forEach(selector => {
        // 清空现有选项
        selector.innerHTML = '<option value="" disabled selected>-- Select an API Type --</option>';
        
        // 添加 API 类型选项
        if (apiTypesData && apiTypesData.items) {
            apiTypesData.items.forEach(type => {
                const option = document.createElement('option');
                option.value = type.xmlKey;
                option.textContent = `${type.itemName} (${type.translationDes})`;
                selector.appendChild(option);
            });
        }

        // 确保事件监听器只添加一次
        selector.removeEventListener('change', handleAPITypeChange);
        selector.addEventListener('change', handleAPITypeChange);
    });
}

// 显示错误信息
function showError(message) {
    console.error('Error:', message);
    // 可以添加更友好的错误提示UI
    alert(message);
}

// 处理 API Type 选择变更
function handleAPITypeChange(event) {
    const select = event.target;
    const selectedValue = select.value;
    console.log('Selected API Type:', selectedValue);

    // 获取相关元素
    const apiTypeItem = select.closest('.api-type-item');
    const purposesSection = apiTypeItem.querySelector('.collection-purposes-section');
    const container = apiTypeItem.querySelector('.api-purposes-container');

    // 清空现有内容
    container.innerHTML = '';

    // 如果没有选择值，隐藏目的列表
    if (!selectedValue) {
        purposesSection.style.display = 'none';
        return;
    }

    // 查找选中的 API 类型数据
    const apiType = apiTypesData.items.find(type => type.xmlKey === selectedValue);
    console.log('Found API type:', apiType);

    if (apiType && apiType.items && apiType.items.length > 0) {
        // 显示收集目的列表区域
        purposesSection.style.display = 'block';

        // 创建目的列表
        const purposesList = document.createElement('div');
        purposesList.className = 'purpose-list';

        // 添加每个目的选项
        apiType.items.forEach((item, index) => {
            const purposeItem = document.createElement('div');
            purposeItem.className = 'purpose-item mb-3 border-bottom pb-3';
            
            // 创建复选框和标签
            const checkboxWrapper = document.createElement('div');
            checkboxWrapper.className = 'form-check';
            
            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.className = 'form-check-input';
            checkbox.id = `purpose_${selectedValue}_${index}`;
            checkbox.value = item.typeKey;
            
            const label = document.createElement('label');
            label.className = 'form-check-label ms-2';
            label.htmlFor = checkbox.id;
            
            // 创建目的内容
            const contentWrapper = document.createElement('div');
            contentWrapper.className = 'purpose-content mt-2 ms-4';
            
            const typeKeyBadge = document.createElement('span');
            typeKeyBadge.className = 'badge bg-secondary me-2';
            typeKeyBadge.textContent = item.typeKey;
            
            const description = document.createElement('div');
            description.className = 'purpose-description mt-2';
            description.textContent = item.explain;
            
            const translation = document.createElement('div');
            translation.className = 'purpose-translation text-muted small mt-2';
            translation.textContent = item.translationDes;
            
            // 组装元素
            checkboxWrapper.appendChild(checkbox);
            checkboxWrapper.appendChild(label);
            
            contentWrapper.appendChild(typeKeyBadge);
            contentWrapper.appendChild(description);
            contentWrapper.appendChild(translation);
            
            purposeItem.appendChild(checkboxWrapper);
            purposeItem.appendChild(contentWrapper);
            purposesList.appendChild(purposeItem);
        });

        // 添加到容器
        container.appendChild(purposesList);
        console.log('Added purposes list to container');
    } else {
        console.log('No purposes found for this API type');
        purposesSection.style.display = 'none';
    }
}

// 添加新的 API Type 项
function addAPITypeItem() {
    const template = document.getElementById('apiTypeTemplate');
    const container = document.getElementById('apiTypesContainer');
    const noItemsMessage = document.getElementById('noAPITypesMessage');
    
    // 克隆模板
    const clone = template.content.cloneNode(true);
    
    // 初始化新项的选择器
    const selector = clone.querySelector('.api-type-select');
    selector.innerHTML = '<option value="" disabled selected>-- Select an API Type --</option>';
    
    if (apiTypesData && apiTypesData.items) {
        apiTypesData.items.forEach(type => {
            const option = document.createElement('option');
            option.value = type.xmlKey;
            option.textContent = `${type.itemName} (${type.translationDes})`;
            selector.appendChild(option);
        });
    }
    
    // 添加事件监听器
    selector.addEventListener('change', handleAPITypeChange);
    
    // 添加删除按钮事件监听器
    const removeButton = clone.querySelector('.remove-api-type');
    removeButton.addEventListener('click', function() {
        this.closest('.api-type-item').remove();
        updateNoItemsMessage();
    });
    
    // 添加到容器
    container.appendChild(clone);
    
    // 更新提示信息显示
    updateNoItemsMessage();
}

// 更新"无项目"提示信息的显示状态
function updateNoItemsMessage() {
    const container = document.getElementById('apiTypesContainer');
    const noItemsMessage = document.getElementById('noAPITypesMessage');
    
    if (container && noItemsMessage) {
        noItemsMessage.style.display = container.children.length > 0 ? 'none' : 'block';
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    loadAPITypes();
    
    const addButton = document.getElementById('addAPIType');
    if (addButton) {
        addButton.addEventListener('click', addAPITypeItem);
    }
});
